package com.itboye.mengwu.main;

import java.util.Observable;
import java.util.Observer;

import android.R.integer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.itboye.core.alert.ByAlert;
import com.itboye.core.cache.ACache;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.SPUtils;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.MainApplication;
import com.itboye.mengwu.app.login.ui.LoginActivity;
import com.itboye.mengwu.app.logincontroller.LoginController;
import com.itboye.mengwu.app.logincontroller.LoginedState;
import com.itboye.mengwu.app.logincontroller.UnLoginState;
import com.itboye.mengwu.app.ui.aiwujia.ActivityAiwujiaMomPublish;
import com.itboye.mengwu.app.ui.main.MainPresenter;
import com.umeng.message.PushAgent;

@SuppressLint("NewApi")
public class MainActivity extends BaseActivity implements Observer,
		OnClickListener, android.widget.CompoundButton.OnCheckedChangeListener {

	private Button btnTest;
	int temp;
	public static int WIDTH;
	private MainPresenter presenter;
	ACache aCache;// 缓存类
	RadioGroup group;
	public Fragment[] fr;
	// private RadioGroup tab_radiogroup;
	private RadioButton[] mTabs;
	private int index;
	private int mCurrIndex;
	int count;
	ImageView zengwuxian_img;
	String uid;
	RelativeLayout fragment_container;

	private ProgressDialog mProgressDialog;
	private final static String TAGS[] = new String[] { "near", "conv",
			"paotui", "gouwuhce", "wo" }; // fragments的tag
	private final static int Tab_Cnt = 5; // 5个tab页

	public void generate() {
		int baseW = 640;
		int baseH = 960;
		String addition = "";

	}

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			System.out.println("执行了2");
			int selectIndex = intent.getIntExtra("index", 0);
			System.out.println("selectIndex" + selectIndex);
			index = selectIndex;
			temp = index;
			setCurrentTab();
		}
	};

	@Override
	public void onMyCreate() {
		// RelativeLayout fragment_container =
		WindowManager manager = this.getWindowManager();
		DisplayMetrics outMetrics = new DisplayMetrics();
		manager.getDefaultDisplay().getMetrics(outMetrics);
		int width2 = outMetrics.widthPixels;

		 //WIDTH = getWindowManager().getDefaultDisplay().getWidth();
		WIDTH = (int) (outMetrics.widthPixels);
		IntentFilter filter = new IntentFilter("set");
		registerReceiver(receiver, filter);
		aCache = ACache.get(this);// 得到缓存对象
		if (isNetworkAvailable(MainActivity.this)) {
			// true
		} else {
			ByAlert.alert("暂时无网络，请查看网络设置");
			return;
		}
		try {
			PushAgent.getInstance(getApplicationContext()).enable();
		} catch (Exception e) {

		}
		if ((Boolean) SPUtils.get(MainApplication.context, null,
				SpPublicParams.IS_LOGINED, false)) {
			LoginController.setLoginState(new LoginedState());
		} else {
			LoginController.setLoginState(new UnLoginState());
		}
		// presenter.register();
		// try {
		// aCache.get("");
		// ////////得到缓存的格式
		// aCache.getAsBinary(key)
		// aCache.getAsBitmap(key)
		// aCache.getAsDrawable(key)
		// aCache.getAsJSONArray(key)
		// aCache.getAsJSONObject(key)
		// aCache.getAsString(key)
		// } catch (FileNotFoundException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }\
		// showProgressDialog(null,"lisi");

		generate();
		initUI();
		initFragments();
	}

	@Override
	public void onSaveInstanceState(Bundle outState,
			PersistableBundle outPersistentState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState, outPersistentState);
	}

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.activity_main;
	}

	@Override
	protected void onSaveInstanceState(Bundle arg0) {
		// TODO Auto-generated method stub
		// super.onSaveInstanceState(arg0);不注释掉，一旦程序出现bug,界面将出现重叠
	}

	// @Override
	// protected void onCreate(Bundle savedInstanceState) {
	// // TODO Auto-generated method stub
	// super.onCreate(savedInstanceState);
	// setContentView(R.layout.activity_main);
	// aCache=ACache.get(this);//得到缓存对象
	// if ((Boolean) SPUtils.get(MainApplication.context, null,
	// SpPublicParams.IS_LOGINED, false)) {
	// LoginController.setLoginState(new LoginedState());
	// }else{
	// LoginController.setLoginState(new UnLoginState());
	// }
	// // presenter.register();
	// // try {
	// // aCache.get("");
	// //////////得到缓存的格式
	// // aCache.getAsBinary(key)
	// // aCache.getAsBitmap(key)
	// // aCache.getAsDrawable(key)
	// // aCache.getAsJSONArray(key)
	// // aCache.getAsJSONObject(key)
	// // aCache.getAsString(key)
	// // } catch (FileNotFoundException e) {
	// // // TODO Auto-generated catch block
	// // e.printStackTrace();
	// // }\
	// // showProgressDialog(null,"lisi");
	// generate();
	// initUI();
	// initFragments();
	// }
	//
	/*
	 * @see java.util.Observer#update(java.util.Observable, java.lang.Object)
	 * 2016-4-23 hebidu
	 */
	@Override
	public void update(Observable observable, Object data) {
		if (count == 0) {
			zengwuxian_img.setBackgroundResource(R.drawable.mamzengsong);
		} else if (count >= 1) {
			zengwuxian_img.setBackgroundResource(R.drawable.fabu);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.zengwuxian_img:
			zengwuxian_img.setBackgroundResource(R.drawable.fabu);
			count++;
			index = 2;
			setCurrentTab();
			Log.e("hu...img", count + "");
			if (count >= 1) {

				uid = SPUtils.get(this, null, SpPublicParams.UID, "") + "";
				if ("".equals(uid) | uid == null) {
					Intent intent = new Intent(this, LoginActivity.class);
					startActivity(intent);
				} else {
					Intent intent = new Intent(this,
							ActivityAiwujiaMomPublish.class);
					startActivity(intent);
				}
			}
			break;
		default:
			break;
		}

	}

	// final protected void showProgressDialog(String title, String msg){
	// mProgressDialog = new ProgressDialog(this);
	// mProgressDialog.setCanceledOnTouchOutside(false);
	// mProgressDialog.setIndeterminate(false);
	// mProgressDialog.setTitle(title);
	// mProgressDialog.setMessage(msg);
	// mProgressDialog.show();
	// }

	private void initUI() {
		// tab_radiogroup = (RadioGroup) findViewById(R.id.tab_radiogroup);
		mTabs = new RadioButton[Tab_Cnt];
		mTabs[0] = (RadioButton) findViewById(R.id.radio_button0);
		mTabs[1] = (RadioButton) findViewById(R.id.radio_button1);
		mTabs[2] = (RadioButton) findViewById(R.id.radio_button2);
		mTabs[3] = (RadioButton) findViewById(R.id.radio_button3);
		mTabs[4] = (RadioButton) findViewById(R.id.radio_button4);
		for (RadioButton bt : mTabs) {
			bt.setOnCheckedChangeListener(this);
		}

	}

	private void setCurrentTab() {
		if (mCurrIndex != index) {
			FragmentTransaction trx = getSupportFragmentManager()
					.beginTransaction();
			trx.hide(fr[mCurrIndex]);
			if (!fr[index].isAdded()) {
				trx.replace(R.id.fragment_container, fr[index]);
			}
			trx.show(fr[index]).commitAllowingStateLoss();
			mTabs[mCurrIndex].setChecked(false);
			mCurrIndex = index;
			if (!mTabs[mCurrIndex].isChecked()) {
				mTabs[mCurrIndex].setChecked(true);// 不会重复触发setCurrentTab
			}

		}
		if (count == 0 && index != 2) {
			zengwuxian_img.setBackgroundResource(R.drawable.mamzengsong);
		} else {

			zengwuxian_img.setBackgroundResource(R.drawable.fabu);
		}
	}

	void initFragments() {
		// TodaySpecialOfferFragmentActivity f1 = null;
		// AiWuJia f2 = null;MengMengCheFragmentActivity f3 =
		// null;ShopCarActivity f4 = null;MengFragment f5 = null;
		fr = new Fragment[] { new HomeFragment(), new AizhiwuFragment(),
				new MomZengFragement(), new FragmentShopcart(),
				new WoMengFragment() };
		// FragmentTransaction
		// fragmentTransaction=getSupportFragmentManager().beginTransaction();
		// if(f1==null){
		// f1=new TodaySpecialOfferFragmentActivity();
		// fragmentTransaction.add(R.id.fragment_container, new
		// TodaySpecialOfferFragmentActivity(),TAGS[0]);
		// }
		// if(f2==null){
		// f2=new AiWuJia();
		// fragmentTransaction.add(R.id.fragment_container, new
		// AiWuJia(),TAGS[1]);
		// }
		// if(f3==null){
		// f3=new MengMengCheFragmentActivity();
		// fragmentTransaction.add(R.id.fragment_container, new
		// MengMengCheFragmentActivity(),TAGS[2]);
		// }
		// if(f4==null){
		// f4=new ShopCarActivity();
		// fragmentTransaction.add(R.id.fragment_container, new
		// ShopCarActivity(),TAGS[3]);
		// }
		// //
		// if(f5==null){
		// f5=new MengFragment();
		// fragmentTransaction.add(R.id.fragment_container, new
		// MengFragment(),TAGS[4]);
		// }
		// fragmentTransaction.hide(fr[1])
		// .hide(fr[2]).hide(fr[3]).hide(fr[4]).show(fr[mCurrIndex]).commit();
		// .add(R.id.fragment_container, fr[0], TAGS[0])
		// .add(R.id.fragment_container, fr[1], TAGS[1])
		// .add(R.id.fragment_container, fr[2], TAGS[2])
		// .add(R.id.fragment_container, fr[3], TAGS[3])
		// .add(R.id.fragment_container, fr[4], TAGS[4]).hide(fr[1])
		// .hide(fr[2]).hide(fr[3]).hide(fr[4]).show(fr[mCurrIndex])
		// fragmentTransaction.hide(fr[1]).hide(fr[2]).hide(fr[3]).hide(fr[4]);
		// fragmentTransaction.show(fr[mCurrIndex]);
		// fragmentTransaction.commit();
		getSupportFragmentManager().beginTransaction()
				.add(R.id.fragment_container, fr[0], TAGS[0])
				.add(R.id.fragment_container, fr[1], TAGS[1])
				.add(R.id.fragment_container, fr[2], TAGS[2])
				.add(R.id.fragment_container, fr[3], TAGS[3])
				.add(R.id.fragment_container, fr[4], TAGS[4]).hide(fr[1])
				.hide(fr[2]).hide(fr[3]).hide(fr[4]).show(fr[mCurrIndex])
				.commit();
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if (isChecked) {
			switch (buttonView.getId()) {
			case R.id.radio_button0:
				index = 0;
				count = 0;
				break;
			case R.id.radio_button1:
				count = 0;
				index = 1;
				break;
			case R.id.radio_button2:
				count = 0;
				index = 2;
				break;
			case R.id.radio_button3:
				count = 1;
				index = 3;
				zengwuxian_img.setBackgroundResource(R.drawable.fabu);
				break;
			case R.id.radio_button4:
				count = 0;
				index = 4;
				try {
					WoMengFragment.setPosition();
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			default:
				break;
			}
			temp = index;
			setCurrentTab();
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(receiver);
	}

	public boolean isNetworkAvailable(Activity activity) {
		Context context = activity.getApplicationContext();
		// 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		if (connectivityManager == null) {
			return false;
		} else {
			// 获取NetworkInfo对象
			NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

			if (networkInfo != null && networkInfo.length > 0) {
				for (int i = 0; i < networkInfo.length; i++) {
					System.out.println(i + "===状态==="
							+ networkInfo[i].getState());
					System.out.println(i + "===类型==="
							+ networkInfo[i].getTypeName());
					// 判断当前网络状态是否为连接状态
					if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}
}
